package com.fuful.servlet;

import com.fuful.domain.Users;
import com.fuful.service.UsersService;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LoginAction extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * 1.获得请求参数所对应的值
         * 2.调用业务逻辑
         * 3.根据逻辑结果选择相应视图(重定向、转发)
         */
        try {
            response.setContentType("text/html");
            response.setCharacterEncoding("utf-8");// 注意设置为UTF-8，否则收到的是中文乱码
            Gson gson = new Gson();
            Map<String, Object> map = new HashMap<String, Object>();

            String userName = request.getParameter("username"); //接收页面传来的用户名
            String passWord = request.getParameter("upwd"); //接收页面传来的密码
            UsersService usersService = new UsersService();
            Users myUser = usersService.login(userName, passWord);

            if (myUser != null) {
                //启Session
                //HttpSession session = request.getSession();
                //session.setAttribute("user",myUser);
                map.put("ret", 1);
                map.put("msg", "登录成功！");

            } else {
                map.put("ret", 0);
                map.put("msg", "用户名或密码错误！");
            }

            String info = gson.toJson(map);
            response.getWriter().print(info);
            response.getWriter().close();
        } catch(Exception e){
            e.getStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }

}
